package com.exception;

import com.broker.base.protocol.response.Resp;
import com.commom.AppRespError;
import com.commom.Config;
import com.echatim.ApplicationWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.ValidationException;


@Slf4j
@Component
public class SocketGlobalExceptionAdvice {
    public Resp<Object> onHandle(Exception e){
        logs(e);
        if(e instanceof ValidationException){
            return handleBindException((ValidationException)e);
        }
        else if(e instanceof ServiceException){
            return Resp.failed(((ServiceException)e).getRespErrorCode());
        }
        else if(e instanceof RuntimeException){
            return Resp.failed(AppRespError.SERVICE_ERROR);
        }
        else {
            return Resp.failed(AppRespError.SERVICE_ERROR);
        }
    }


    private Resp<Object>  handleBindException(ValidationException ex){
        String errorStart = "参数校验错误:";
        return Resp.failed(errorStart + ex.toString(), AppRespError.REQUEST_VERIFY_ERROR.getCode());
    }

    private void logs(Exception e){
        if("storagesync".equals(Config.get(ApplicationWrapper.getContext(), "spring.profiles.active"))){
            e.printStackTrace();
        }
        else {
            log.error(" error: ", e);
        }
    }
}
